package cn.cs.controller;

import cn.cs.client.RestClientUserClient;
import cn.cs.client.RestRepairUserClient;
import cn.cs.common.Dto;
import cn.cs.common.DtoUtil;
import cn.cs.common.EmptyUtils;
import cn.cs.common.RedisUtils;
import cn.cs.pojo.RepairOrder;
import cn.cs.pojo.User;
import cn.cs.service.RepairOrderService;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/repairOrder")
public class RepairOrderController {
    @Resource
    private RepairOrderService repairOrderService;
    @Resource
    private RedisUtils redisUtils;

    @Resource
    private RestClientUserClient clientUserClient;

    @Resource
    private RestRepairUserClient repairUserClient;


    /**
     *根据用户Id 查询用户所下过预约单类型
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxApi/getUserOrderType")
    @ResponseBody
    public Dto getUserOrderType(String userId) throws Exception {
        return DtoUtil.returnSuccess("获取成功",repairOrderService.getUserOrderType(userId));
    }


    /**
     * 客户端跟踪订单信息
     */
    @RequestMapping("/wxApi/getRepairOrderByUserId")
    @ResponseBody
    public Dto getRepairOrderByUserId(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //表示用户已经登录
        String userId = request.getParameter("userId");//用户ID
        int pageNumber = Integer.valueOf(request.getParameter("pageNumber"));//起始页码
        int pageSize = Integer.valueOf(request.getParameter("pageSize"));//每页多少条
        String userType = request.getParameter("userType");//用户类型 0个人用户 1企业用户 2电器厂家用户
        String isProtect = request.getParameter("isProtect");//是否质保（0否1是）
        String isRepair = request.getParameter("isRepair");//是否维修（0否1是）
        String orderState = request.getParameter("orderState");//预约单状态 0未接单 1已接单 2已检测 3已支付 4已评价 5已取消
        String phone = clientUserClient.getClientUserById(userId).getPhone();
        Map<String, Object> map = new HashMap<>();
        map.put("pageNumber", pageNumber);
        map.put("pageSize", pageSize);
        map.put("userType", userType);
        map.put("isProtect", isProtect);
        map.put("isRepair", isRepair);
        map.put("orderState", orderState);
        map.put("userId", userId);
        map.put("phone", phone);
        //根据用户ID，获取用户的订单信息
        return DtoUtil.returnSuccess("查询成功", repairOrderService.getAppOrderById(map));
    }

    /**
     * 修改订单状态接口
     */
    @RequestMapping("/wxApi/updateRepairOrderState")
    @ResponseBody
    public Dto updateRepairOrderState(HttpServletRequest request) {
        Dto dto = null;
        try {
            String id = request.getParameter("id");
            String orderState = request.getParameter("orderState");

            dto = repairOrderService.updateRepairOrder(request, id, orderState);
            if (dto != null) {
                DtoUtil.returnSuccess("更改状态成功", "0000");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("更改状态失败", "0002");
        }
        return dto;
    }

    /**
     * 订单中心
     */
    @RequestMapping("/wxApi/getOrderInfo")
    @ResponseBody
    public Dto<RepairOrder> getOrderInfo(HttpServletRequest request) throws Exception {
        Dto dto = new Dto();
        String token = request.getHeader("token");
        User user = JSON.parseObject(redisUtils.get(token).toString(), User.class);
        if (EmptyUtils.isEmpty(user)) {
            return DtoUtil.returnFail("用户未登录", "0001");
        }
        String userId = user.getId();
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", userId);
            List<Map<String, Object>> list = repairOrderService.getAppOrderById(map);
            dto.setData(list);
            if (dto != null) {
                DtoUtil.returnSuccess("查询成功", "0000");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("查询失败", "0002");
        }
        return dto;
    }

    /**
     * 根据订单状态获取预约单信息
     */
    @RequestMapping("/wxApi/getAppOrderByOrderState")
    @ResponseBody
    public Dto<RepairOrder> getAppOrderByOrderState(HttpServletRequest request, String orderState) throws Exception {
        Dto dto = new Dto();
        try {
            List<Map<String, Object>> list = repairOrderService.getAppOrderByOrderState(orderState);
            dto.setData(list);

            if (dto != null) {
                DtoUtil.returnDataSuccess("true,0000");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("失败", "0002");
        }
        return dto;
    }

    /**
     * 余额支付(订单可以微信支付，也可以余额支付)
     * orderNo 订单编号 countSum 总金额
     */
    @RequestMapping("/wxApi/userBalancePay")
    public Dto userBalancePay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userId = request.getParameter("userId");
        if(EmptyUtils.isEmpty(userId)){
            return DtoUtil.returnFail("用户不存在，请重新授权登陆", "userNull001");
        }
        String orderNo = request.getParameter("orderNo");
        Double countSum = Double.parseDouble(request.getParameter("countSum"));
        //修改账户余额，添加账户信息变动，修改订单状态
        return repairOrderService.userBalancePay(orderNo, userId, countSum);
    }

    /**
     * 余额支付(订单可以微信支付，也可以余额支付)
     * orderNo 订单编号 countSum 总金额
     */
    @RequestMapping("/dqcApi/userBalancePayDQC")
    public Dto userBalancePayDQC(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userId = request.getParameter("userId");
        if(EmptyUtils.isEmpty(userId)){
            return DtoUtil.returnFail("用户不存在，请重新授权登陆", "userNull001");
        }
        String factoryId = request.getParameter("factoryId");
        String orderNo = request.getParameter("orderNo");
        Double countSum = Double.parseDouble(request.getParameter("countSum"));
        //修改账户余额，添加账户信息变动，修改订单状态
        return repairOrderService.userBalancePayDQC(orderNo, userId, countSum, factoryId);
    }


    /**
     * 查询检测报告是否支付
     * orderNo 订单编号 countSum 总金额
     */
    @RequestMapping("/wxApi/getTestReportById")
    public Dto getTestReportById(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String orderNo = request.getParameter("orderNo");
        Map<String, Object> map = repairOrderService.getTestReportById(orderNo);
        String pay_status = map.get("pay_status").toString();
        if("1".equals(pay_status)){
            return DtoUtil.returnFail("已支付，请勿重复支付", "001");
        }
        return DtoUtil.returnSuccess("未支付，可以支付", map);
    }

    /**
     * 余额支付检测报告(订单可以微信支付，也可以余额支付)
     * orderNo 订单编号 countSum 总金额
     */
    @RequestMapping("/wxApi/userBalancePayTestReport")
    public Dto userBalancePayTestReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userId = request.getParameter("userId");
        if(EmptyUtils.isEmpty(userId)){
            return DtoUtil.returnFail("用户不存在，请重新授权登陆", "userNull001");
        }
        String orderNo = request.getParameter("orderNo");
        String _countSum = request.getParameter("countSum");
        Double countSum = Double.parseDouble(_countSum);
        //修改账户余额，添加账户信息变动，修改订单状态
        return repairOrderService.userBalancePayTestReport(orderNo, userId, countSum);
    }

    /**
     * 查询账单信息
     */
    @RequestMapping("/wxApi/queryOrderCountDetail")
    public Dto queryOrderCountDetail(String orderId) throws Exception {
        return DtoUtil.returnSuccess("查询成功", repairOrderService.getOrderDetailsByOrderId(orderId));
    }

    /**
     * 客户端跟踪订单信息 -- pc
     */
    @RequestMapping("/csPlatform/getRepairOrder")
    @ResponseBody
    public Dto getRepairOrder(HttpServletRequest request) throws Exception {
        String userId = request.getParameter("userId");//用户ID
        int pageNumber = Integer.valueOf(request.getParameter("pageNumber"));//起始页码
        int pageSize = Integer.valueOf(request.getParameter("pageSize"));//每页多少条
        String userType = request.getParameter("userType");//用户类型 0个人用户 1企业用户 2电器厂家用户
        String isProtect = request.getParameter("isProtect");//是否质保（0否1是）
        String isRepair = request.getParameter("isRepair");//是否维修（0否1是）
        String orderState = request.getParameter("orderState");//预约单状态 0未接单 1已接单 2已检测 3已支付 4已评价 5已取消
        String phone = request.getParameter("phone");//用户手机号
        String overtime = request.getParameter("overtime");//超时未接单标志
        String afterOrderId = request.getParameter("afterOrderId");//售后订单id

        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("userType", userType);
        map.put("isProtect", isProtect);
        map.put("isRepair", isRepair);
        map.put("orderState", orderState);
        map.put("phone", phone);
        map.put("overtime", overtime);
        map.put("afterOrderId", afterOrderId);
        if(EmptyUtils.isNotEmpty(userId)){
            String userPhone = clientUserClient.getClientUserById(userId).getPhone();
            map.put("userPhone", userPhone);
        }
        //根据用户ID，获取用户的订单信息
        return DtoUtil.returnSuccess("查询成功", repairOrderService.queryRepairOrderPageByMap(map, pageNumber, pageSize));
    }


    /**
     * 客户端跟踪订单信息 -- 维修工维修单管理 -- pc
     */
    @RequestMapping("/csPlatform/getRepairOrderRepairUser")
    @ResponseBody
    public Dto getRepairOrderRepairUser(HttpServletRequest request) throws Exception {
        int pageNumber = Integer.valueOf(request.getParameter("pageNumber"));//起始页码
        int pageSize = Integer.valueOf(request.getParameter("pageSize"));//每页多少条
        String userType = request.getParameter("userType");//用户类型 0个人用户 1企业用户 2电器厂家用户
        String isProtect = request.getParameter("isProtect");//是否质保（0否1是）
        String isRepair = request.getParameter("isRepair");//是否维修（0否1是）
        String orderState = request.getParameter("orderState");//预约单状态 0未接单 1已接单 2已检测 3已支付 4已评价 5已取消
        String phone = request.getParameter("phone");//维修工手机号
        String userPhone = request.getParameter("userPhone");//用户手机号
        String id = request.getParameter("id");//订单号，id
        String rep_user_id = request.getParameter("rep_user_id");//订单号，id
        Map<String, Object> map = new HashMap<>();
        map.put("userType", userType);
        map.put("isProtect", isProtect);
        map.put("isRepair", isRepair);
        map.put("orderState", orderState);
        map.put("phone", phone);
        map.put("userPhone", userPhone);
        map.put("id", id);
        map.put("rep_user_id", rep_user_id);
        List<Map<String, Object>> list = repairUserClient.getRepairUserByLikePhone(phone, null);
        map.put("list", list);
        //根据用户ID，获取用户的订单信息
        return DtoUtil.returnSuccess("查询成功", repairOrderService.queryRepairOrderRepairUserPageByMap(map, pageNumber, pageSize));
    }


    /**
     * 获取A级经销商结算详细 -- pc
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/csPlatform/getRepairOrderAgentAPageByMap")
    @ResponseBody
    public Dto getRepairOrderAgentAPageByMap(HttpServletRequest request) throws Exception {
        int pageNumber = Integer.valueOf(request.getParameter("pageNumber"));//起始页码
        int pageSize = Integer.valueOf(request.getParameter("pageSize"));//每页多少条
        String parentInvitationCode  = request.getParameter("invitationCode");//经销商邀请码
        String typeId  = request.getParameter("typeId");//经销商分类id
        String area  = request.getParameter("area");//经销商管辖区域
        String agentId = request.getParameter("agentId");//经销商id
        Map<String, Object> map = new HashMap<>();
        map.put("parentInvitationCode", parentInvitationCode );
        map.put("typeId", typeId );
        map.put("area", area );
        map.put("agentId", agentId );
        //根据用户ID，获取用户的订单信息
        return DtoUtil.returnSuccess("查询成功", repairOrderService.queryRepairOrderAgentAPageByMap(map, pageNumber, pageSize));
    }

    /**
     * 结算日期，查询经销商的待结算 订单明细，金额 -- pc
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/csPlatform/queryRepairOrderAgentProfitAll")
    @ResponseBody
    public Dto queryRepairOrderAgentProfitAll(HttpServletRequest request) throws Exception {
        String parentInvitationCode  = request.getParameter("invitationCode");//经销商邀请码
        String typeId  = request.getParameter("typeId");//经销商分类id
        String area  = request.getParameter("area");//经销商管辖区域
        String agentId = request.getParameter("agentId");//经销商id
        Map<String, Object> map = new HashMap<>();
        map.put("parentInvitationCode", parentInvitationCode );
        map.put("typeId", typeId );
        map.put("area", area );
        map.put("agentId", agentId );
        //根据用户ID，获取用户的订单信息
        return repairOrderService.queryRepairOrderAgentProfitAll(map);
    }


    /**
     * 分页查询 维修工缴纳保险详情-- pc
     * @param pageNumber
     * @param pageSize
     * @param personName
     * @param phone
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/csPlatform/getRepairInsurancePage")
    public Dto getFaultTypeList(Integer pageNumber, Integer pageSize, String personName, String phone, String startDate, String endDate)throws Exception{
        Map<String, Object> param = new HashMap<>();
        param.put("personName", personName);
        param.put("phone", phone);
        if(EmptyUtils.isNotEmpty(startDate)){
            param.put("startDate", startDate + "00:00:00");
        }
        if(EmptyUtils.isNotEmpty(endDate)){
            param.put("endDate", endDate + "23:59:59");
        }
        List<Map<String, Object>> list = repairUserClient.getRepairUserByLikePhone(phone, personName);
        param.put("list", list);
        return DtoUtil.returnSuccess("获取成功", repairOrderService.queryRepairInsurancePageByMap(param, pageNumber, pageSize));
    }
}